package com.cgwx.service.impl;

import com.cgwx.common.utils.PostUtil;
import com.cgwx.config.BusinessException;
import com.cgwx.entity.FsTransmitDetail;
import com.cgwx.entity.FsTransmitRecord;
import com.cgwx.entity.File;
import com.cgwx.mapper.FsTransmitDetailMapper;
import com.cgwx.service.IFileService;
import com.cgwx.service.IFsTransmitDetailService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class FsTransmitDetailServiceImpl implements IFsTransmitDetailService {

    @Resource
    private IFileService fileService;

    @Resource
    private FsTransmitDetailMapper fsTransmitDetailMapper;

    @Value("${file_manage.address}")
    private String fileManageAddress;

    @Value("${file_manage.port}")
    private int fileManagePort;

    @Override
    public List<FsTransmitDetail> getFsTransmitDetail(FsTransmitDetail fsTransmitDetail) {
        return fsTransmitDetailMapper.getFsTransmitDetail(fsTransmitDetail);
    }

    @Transactional
    @Override
    public boolean updateFsTransmitDetail(String taskId, Map<String, String> map) {
        FsTransmitDetail fsTransmitDetailSearch = new FsTransmitDetail();
        fsTransmitDetailSearch.setTaskId(taskId);
        List<FsTransmitDetail> fsTransmitDetailList = getFsTransmitDetail(fsTransmitDetailSearch);
        log.info("map: {}", map.toString());
        for(FsTransmitDetail fsTransmitDetail : fsTransmitDetailList) {
            log.info("getKeyId: {}", fsTransmitDetail.getKeyId());
            if(map.containsKey(fsTransmitDetail.getKeyId())) fsTransmitDetail.setStatus("查杀通过待传输");
            else fsTransmitDetail.setStatus("查杀不通过");
            if(!fsTransmitDetailMapper.updateFsTransmitDetail(fsTransmitDetail)){
                log.warn("updateTransmitTask文件传输详情修改失败!{}", fsTransmitDetail);
                throw new BusinessException("updateTransmitTask文件传输详情修改失败!" + fsTransmitDetail);
            }
        }
        return true;
    }

    @Transactional
    @Override
    public boolean completeFsTransmitDetail(String taskId, Map<String, String> map, LocalDateTime time, String path) {
        FsTransmitDetail fsTransmitDetailSearch = new FsTransmitDetail();
        fsTransmitDetailSearch.setTaskId(taskId);
        List<FsTransmitDetail> fsTransmitDetailList = getFsTransmitDetail(fsTransmitDetailSearch);
        log.info("map: {}", map);
        for(FsTransmitDetail fsTransmitDetail : fsTransmitDetailList) {
            fsTransmitDetail.setCompleteTime(time);
            log.info("getKeyId: {}", fsTransmitDetail.getKeyId());
            if(map.containsKey(fsTransmitDetail.getKeyId())){
                fsTransmitDetail.setStatus("上传成功");
                File file = new File();
                file.setFileId(map.get(fsTransmitDetail.getKeyId()));
                file = fileService.getFile(file).get(0);
                fsTransmitDetail.setEntityId(file.getEntityId());
            }
            if(!fsTransmitDetailMapper.updateFsTransmitDetail(fsTransmitDetail)){
                log.warn("completeFsTransmitDetail文件传输详情修改失败!{}", fsTransmitDetail);
                throw new BusinessException("completeFsTransmitDetail文件传输详情修改失败!" + fsTransmitDetail);
            }
        }
        FsTransmitDetail fsTransmitDetail = fsTransmitDetailList.get(0);
        try {
            int success = map.size();
            int fail = fsTransmitDetailList.size() - map.size();
            String text = "【外网文件传输】您于" + path + "上传的文件传输完成，结果如下:文件总数:"
                    + fsTransmitDetailList.size() + "\n" + "上传成功数:" + success + "\n";
            if(fail > 0) text += "病毒风险拦截数:" + fail + "，该" + fail + "个文件已删除\n";
            text += "可于内网【长光卫星信息化服务平台】-【协同办公】-【文件中心】-【个人空间】查看文件传输详情。";
            PostUtil.sendWechat(fsTransmitDetail.getOwnerAccount(), text);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        return true;
    }

    @Override
    @Transactional
    public boolean insertFsTransmitDetail(FsTransmitRecord fsTransmitRecord, String jsonString) {
        FsTransmitDetail fsTransmitDetail = new FsTransmitDetail();
        fsTransmitDetail.setTaskId(fsTransmitRecord.getId());
        fsTransmitDetail.setPath(fsTransmitRecord.getPath());
        fsTransmitDetail.setParentId(fsTransmitRecord.getParentId());
        fsTransmitDetail.setStatus("病毒查杀中");
        fsTransmitDetail.setOwnerAccount(fsTransmitRecord.getOwnerAccount());
        fsTransmitDetail.setOwnerName(fsTransmitRecord.getOwnerName());
        JSONArray jsonArray = new JSONArray(jsonString);
        for(int i = 0; i < jsonArray.length(); i++){
            JSONObject object = jsonArray.getJSONObject(i);
            fsTransmitDetail.setId(generateId());
            fsTransmitDetail.setFileName(object.getString("fileName"));
            fsTransmitDetail.setFileType(object.getString("fileType"));
            fsTransmitDetail.setFileSize(object.getString("fileSize"));
            fsTransmitDetail.setKeyId(object.getString("keyId"));
            if(!fsTransmitDetailMapper.insertFsTransmitDetail(fsTransmitDetail)){
                log.warn("新增文件传输详情失败!{}", fsTransmitDetail);
                return false;
            }
        }
        return true;
    }

    public String generateId() {
        return UUID.randomUUID().toString();
    }
}
